
import userApi from '@/api/user';
import shopApi from '@/api/shop';
import userSotre  from '@/store/user';
import {APP_ID} from "@/config/app";
const userPinia = userSotre()


export function getUserIphone(e, callback) {//获取手机号
	console.log("errMsg", e.detail.errMsg)
	if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
		console.log('用户拒绝提供手机号');
	} else {
		console.log('用户同意提供手机号', e);
		console.log("iv", e.detail.iv)
		console.log("encryptedData", e.detail.encryptedData)
		let encryptedData = e.detail.encryptedData
		let iv = e.detail.iv
		let code = e.detail.code
		userApi.Iphone({ code: code,appId:APP_ID }).then(res => {
			userPinia.setIphone(res.data)
			if (callback) {
				callback()
			}
		})
	}
}


export function getPhone(code) {//发送手机号到后端解密
	userApi.Iphone({
		code: code,
		appId:APP_ID
	}).then(res => {
		userPinia.setIphone(res.data)
	})
}

export function getOpenId(code) {  //通过code获取openId
	let obj = {
		code: code,
		appId:APP_ID
	}
	userApi.getOpenId(obj).then((res: any) => {
		let openId = res.data.data
		console.log('getOpenId回调', openId);

	})

}
export function Login(e, callback) {//登录
	toLogin(e, callback)
}

export function toLogin(e, callback) {//已注册直接登录
	let obj = {
		openId: uni.getStorageSync("openId"),
		userRole: userPinia.userRole
	}
	userApi.toLogin(Object.assign(obj, e)).then(async (res) => {
		uni.setStorageSync('token', res.data.userCode)
			uni.setStorageSync('openId', res.data.openId)
		userPinia.setUserinfo({...res.data,...res.data.object})
		userPinia.setUserRole(res.data.userRole)

		if (res.data.userRole == 3) {//商户
			let { data: shopList } = await shopApi.getShopListAll({})
			if (shopList.length > 0) {
				userPinia.setShopId(shopList[0].id)
				userPinia.setAllowMonthSettle(shopList[0].allowMonthSettle)
				userPinia.$patch((state) => {
					state.userinfo.nickName = shopList[0].name
				})
			}
		} else if (res.data.userRole == 4) {//服务员
			userPinia.setShopId("")
			if(res.data.detailRole ==2){
				userPinia.setPublicUser()
			}
		}
		if (callback) {
			callback()
		}
	})
}

export function loginOut(callback) {//退出登录

	uni.showModal({
		title: '提示',
		content: '是否确认退出登录',
		success: (rsult) => {
			if (rsult.confirm) {
				userApi.outLogin({}).then(res => {
					//清空缓存
					uni.removeStorageSync('user')
					if (callback) {
						callback()
					}
				})

			} else if (rsult.cancel) {

			}
		}
	})

}


export function toRelogin() {//未注册 > 去注册

}
